package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.PaymentAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.alipay.PayResult;
import com.eightbears.beboy.base.cache.MyAddressCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.PasswordPayPopup;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.HongBaoEntity;
import com.eightbears.beboy.entity.OrderDetailEntity;
import com.eightbears.beboy.entity.OrderEntity;
import com.eightbears.beboy.entity.PayInfoEntity;
import com.eightbears.beboy.entity.PayOrderEntity;
import com.eightbears.beboy.entity.PayTypeEntity;
import com.eightbears.beboy.entity.PostInfoEntity;
import com.eightbears.beboy.entity.ProductEntity;
import com.eightbears.beboy.entity.ProductsEntity;
import com.eightbears.beboy.entity.ShoppingAddressEntity;
import com.eightbears.beboy.entity.WeChatPayEntity;
import com.eightbears.beboy.entity.event.RedSelectEvent;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.entity.status.Status_ShopDetail;
import com.eightbears.beboy.ui.login.ForgetActivity;
import com.eightbears.greendao.MyAddress;
import com.makeramen.roundedimageview.RoundedImageView;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_ALIPAY;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_MYPAY;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_WEIXIN;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_GETALLADDRESS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHARE_CALL_BACK;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_RED;
import static com.eightbears.beboy.base.util.CommonAPI.WECHAT_APP_ID;
import static com.eightbears.beboy.entity.PayTypeEntity.TYPE_ALIPAY;
import static com.eightbears.beboy.entity.PayTypeEntity.TYPE_MYPAY;
import static com.eightbears.beboy.entity.WaitPaymentEntity.PARAMS_WAIT_PAYMENT;
import static com.eightbears.beboy.ui.merchant.activity.ShopPaymentActivity.PARAMS_GET_MONEY_2_SHOP;
import static com.eightbears.beboy.ui.user.activity.AddShoppingAddressActivity.EVENT_ADDRESS_SUCCESS;
import static com.eightbears.beboy.ui.user.activity.ByVipActivity.PARAMS_BUY_VIP;
import static com.eightbears.beboy.ui.user.activity.CommodityDetailActivity.PARAMS_SHOP_COMMODITY;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_BUY_SETWEAL;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_ORDER_DETAIL;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_ORDER_INFO;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_PAY_ORDER;
import static com.eightbears.beboy.ui.user.activity.TransferActivity.PARAMS_PAY_TRANSFER;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_BUY_POST;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ITEM;
import static com.socks.library.KLog.e;

public class PaymentActivity extends BaseActivity {

    public static final String PARAMS_RED_TYPE = "redType";
    public static final String EVENT_WCHAT_PAY_SUCCESS = "wCHatPaySuccess";
    public static final String PARAMS_MEAL_DETAIL = "mealDetail";
    public static final String EVENT_MY_PAY = "myPay";


    public static final int SDK_PAY_FLAG = 1;

    public static final String PARAMS_BAY_POST = "1";
    public static final String PARAMS_BAY_COMMODITY = "2";
    public static final String PARAMS_BAY_RED = "3";
    public static final String PARAMS_BAY_SETMEAL = "4";
    public static final String PARAMS_BAY_SHOPTRANSFER = "3";//转账商家
    public static final String PARAMS_BAY_USERTRANSFER = "5";//转账给用户


    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_order_title)
    TextView tv_order_title;
    @BindView(R.id.tv_discount_price)
    TextView tv_discount_price;
    @BindView(R.id.tv_cost_price)
    TextView tv_cost_price;
    @BindView(R.id.tv_red_count)
    TextView tv_red_count;
    @BindView(R.id.tv_total)
    TextView tv_total;
    @BindView(R.id.tv_date)
    TextView tv_date;
    @BindView(R.id.rl_address)
    RelativeLayout rl_address;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
    @BindView(R.id.ll_setting_address)
    LinearLayout ll_setting_address;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.iv_shopbook_image)
    RoundedImageView iv_shopbook_image;
    @BindView(R.id.ll_money)
    LinearLayout ll_money;
    @BindView(R.id.rl_end_date)
    RelativeLayout rl_end_date;
    @BindView(R.id.rl_red_package)
    RelativeLayout rl_red_package;
    @BindView(R.id.ll_view_title)
    LinearLayout ll_view_title;
    @BindView(R.id.tv_shop_name)
    TextView tv_shop_name;
    @BindView(R.id.ll_money_pay)
    LinearLayout ll_money_pay;
    @BindView(R.id.rl_total_money)
    RelativeLayout rl_total_money;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.iv_vip)
    ImageView iv_vip;
    @BindView(R.id.ll_shop_payinfo)
    LinearLayout ll_shop_payinfo;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;

    private PaymentAdapter mPaymentAdapter;

    private HomeListEntity.Post post;
    private ProductsEntity productsEntity;
    private HongBaoEntity.HongBao mHongBao;
    private OrderDetailEntity.Order orderDetailEntity;
    private PayOrderEntity.PayOrder waitPaymentEntity;
    private OrderEntity.OrderInfo orderInfo;
    private OrderEntity.OrderDetailEntity orderDetail;
    private ProductEntity productEntity;
    private Status_ShopDetail status_shopDetail;
    private PasswordPayPopup mPasswordPayPopup;

    private String payPlatform = TYPE_MYPAY;
    private String payType;
    private String myAddressId = "0";
    private String commodityId = "";
    private String hongbaoId = "0";
    private String hongBaoCount = "0";

    private String transfer_money = "0";
    private String type;
    private String money;
    private String mPrice;
    private String mTitle;
    private double mPrice1;
    private double price;
    private PayInfoEntity mPayInfoEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_ment);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_payment);
        tv_loading_text.setText(R.string.text_payment);
        post = (HomeListEntity.Post) getExtras().get(PARAMS_BUY_POST);
        productsEntity = (ProductsEntity) getExtras().get(PARAMS_BUY_VIP);
        orderDetailEntity = (OrderDetailEntity.Order) getExtras().get(PARAMS_BUY_SETWEAL);
        waitPaymentEntity = (PayOrderEntity.PayOrder) getExtras().get(PARAMS_WAIT_PAYMENT);
        orderInfo = (OrderEntity.OrderInfo) getExtras().get(PARAMS_ORDER_INFO);
        productEntity = (ProductEntity) getExtras().get(PARAMS_SHOP_COMMODITY);
        status_shopDetail = (Status_ShopDetail) getExtras().get(PARAMS_GET_MONEY_2_SHOP);
        orderDetail = (OrderEntity.OrderDetailEntity) getExtras().get(PARAMS_PAY_ORDER);

        initAdapter();

        if (null != post) {
            initPostView();
        }

        if (null != productsEntity) {
            buyVip();
        }

        if (null != orderDetailEntity) {
            initCoupons();
        }

        if (null != orderInfo) {
            initOrderInfo();
        }

        if (null != orderDetail) {
            initOrderList();
        }

        if (null != waitPaymentEntity) {
            initWaitPayment();
        }

        if (null != productEntity) {
            getUserAddressData();
        }

        if (null != status_shopDetail) {
            type = HongBaoEntity.TYPE_SHOPPAY;
            initShopPayment();
        }
    }


    @Override
    protected void initData() {
        getRed();
    }

    @Override
    protected void initEvent() {
        mPaymentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.ll_item:
                        mPaymentAdapter.checked(position);
                        KLog.e(view.getTag().toString());
                        payPlatform = view.getTag().toString();
                        break;
                }
            }
        });
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }


    private void initAdapter() {
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        mPaymentAdapter = new PaymentAdapter();
        List<PayTypeEntity> list = PayTypeEntity.getPayList();
        mPaymentAdapter.setNewData(list);
        mPaymentAdapter.checked(0);
        rv_list.setAdapter(mPaymentAdapter);
    }

    // 初始化帖子购买界面
    private void initPostView() {
        commodityId = post.getRepost_id() == 0 ? post.getId() + "" : post.getRepost_id() + "";
        payType = PARAMS_BAY_POST;
        type = HongBaoEntity.TYPE_POST;
        // 界面
        ll_view_title.setVisibility(View.GONE);
        rl_end_date.setVisibility(View.GONE);
        ll_money.setVisibility(View.GONE);

        // 数据
        String nickName = post.getRepost_id() == 0 ?
                post.getUser().getNickname() + "" : post.getRepost().getNickname();
        price = post.getRepost_id() == 0 ? post.getPrice() : post.getRepost().getPrice();
        mPrice = String.format(mContext.getText(R.string.text_price).toString(), price);
        mTitle = String.format(mContext.getText(R.string.text_by_who).toString(), nickName);
        tv_order_title.setText(mTitle);
        tv_discount_price.setText(mPrice);
        tv_total.setText(mPrice);
        if (null != post.getImages())
            CommonUtils.loadImageView(getApplication(), post.getImages().get(0), R.mipmap.default_icon, iv_shopbook_image);
        else
            CommonUtils.loadImageView(getApplication(), "", R.mipmap.default_icon, iv_shopbook_image);

    }

    // 初始化购买VIP
    private void buyVip() {
        payType = PARAMS_BAY_COMMODITY;
        commodityId = productsEntity.getProduct_id();

        rl_red_package.setVisibility(View.GONE);
        ll_view_title.setVisibility(View.GONE);
        ll_money.setVisibility(View.GONE);
        rl_total_money.setVisibility(View.GONE);
        iv_shopbook_image.setVisibility(View.GONE);

        int vipImg = productsEntity.getProduct_id().equals("1") ? R.mipmap.icon_vip1 : R.mipmap.icon_vip2;
        String priceFormat = String.format(mContext.getText(R.string.text_price).toString(), productsEntity.getMoney());
        tv_order_title.setText(productsEntity.getTitle());
        tv_discount_price.setText(priceFormat);
        iv_vip.setVisibility(View.VISIBLE);
        String validDate = String.format(getString(R.string.text_vip_valid_date)
                , (Integer.parseInt(productsEntity.getValidity()) / 3600 / 24) + "");
        tv_date.setText(validDate);
        CommonUtils.loadImageView(getApplication(), "", vipImg, iv_vip);

    }

    private void initCoupons() {
        type = HongBaoEntity.TYPE_MONEY;
        money = orderDetailEntity.getDiscount_price();
        commodityId = orderDetailEntity.getId();
        payType = PARAMS_BAY_SETMEAL;
        mPrice = String.format(getString(R.string.text_price), orderDetailEntity.getDiscount_price());
        String price = String.format(getString(R.string.text_price), orderDetailEntity.getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(orderDetailEntity.getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(orderDetailEntity.getEnd_at(), "yyyy-MM-dd"));

        tv_discount_price.setText(mPrice);
        tv_total.setText(mPrice);

        tv_cost_price.setText(price);
        CommonUtils.loadImageView(getApplication(), orderDetailEntity.getCover(),
                R.mipmap.icon_default_shop, iv_shopbook_image);
        mTitle = orderDetailEntity.getTitle();
        tv_order_title.setText(mTitle);
        tv_shop_name.setText(orderDetailEntity.getShop().getTitle());
        tv_date.setText(date);

    }

    private void initOrderInfo() {
        type = HongBaoEntity.TYPE_MONEY;
        money = orderInfo.getCoupon().getDiscount_price();
        commodityId = orderInfo.getCoupon().getId();
        payType = PARAMS_BAY_SETMEAL;
        String disPrice = String.format(getString(R.string.text_price), orderInfo.getCoupon().getDiscount_price());
        String price = String.format(getString(R.string.text_price), orderInfo.getCoupon().getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(orderInfo.getCoupon().getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(orderInfo.getCoupon().getEnd_at(), "yyyy-MM-dd"));
        tv_discount_price.setText(disPrice);
        tv_total.setText(disPrice);
        tv_cost_price.setText(price);
        CommonUtils.loadImageView(getApplication(), orderInfo.getCoupon().getCover(),
                R.mipmap.icon_default_shop, iv_shopbook_image);
        tv_order_title.setText(orderInfo.getCoupon().getTitle());
        tv_shop_name.setText(orderInfo.getShop().getTitle());
        tv_date.setText(date);
    }

    private void initOrderList() {
        type = HongBaoEntity.TYPE_MONEY;
        money = orderDetail.getData().getAmount();
        commodityId = orderDetail.getData().getCoupon_id();
        payType = PARAMS_BAY_SETMEAL;
        String disPrice = String.format(getString(R.string.text_price), orderDetail.getData().getAmount());
        String price = String.format(getString(R.string.text_price), orderDetail.getData().getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(orderDetail.getData().getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(orderDetail.getData().getEnd_at(), "yyyy-MM-dd"));
        tv_discount_price.setText(disPrice);
        tv_total.setText(disPrice);
        tv_cost_price.setText(price);
        CommonUtils.loadImageView(getApplication(), orderDetail.getData().getCover(),
                R.mipmap.icon_default_shop, iv_shopbook_image);
        tv_order_title.setText(orderDetail.getData().getTitle());
        tv_shop_name.setText(orderDetail.getData().getShop().getTitle());
        tv_date.setText(date);
    }


    private void initWaitPayment() {
        type = HongBaoEntity.TYPE_MONEY;
        money = waitPaymentEntity.getTotal_amount();
        payType = PARAMS_BAY_SETMEAL;
        commodityId = waitPaymentEntity.getObject_id();

        String disPrice = String.format(getString(R.string.text_price),
                money);
        String price = String.format(getString(R.string.text_price),
                waitPaymentEntity.getObject().getPrice());
        tv_discount_price.setText(disPrice);
        tv_cost_price.setText(price);
        tv_total.setText(disPrice);
        tv_shop_name.setText(waitPaymentEntity.getObject().getShop().getTitle());
        tv_order_title.setText(waitPaymentEntity.getObject().getTitle());
        CommonUtils.loadImageView(this, waitPaymentEntity.getObject().getCover(), R.mipmap.icon_default_shop, iv_shopbook_image);
        rl_red_package.setVisibility(View.GONE);
        if (waitPaymentEntity.getChannel().equals(TYPE_ALIPAY)) {
            mPaymentAdapter.getData().remove(1);
            mPaymentAdapter.notifyDataSetChanged();
            mPaymentAdapter.checked(0);
            payPlatform = TYPE_ALIPAY;
        } else {
            mPaymentAdapter.getData().remove(0);
            mPaymentAdapter.notifyDataSetChanged();
            mPaymentAdapter.checked(0);
            payPlatform = PayTypeEntity.TYPE_WCHAT;
        }
    }

    /**
     * 获取用户收货地址数据
     */
    public void getUserAddressData() {
        OkHttpUtils.get().url(URL_RESET_GETALLADDRESS)
                .addHeader(CommonAPI.KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShoppingAddressEntity shoppingAddressEntity = GsonUtil.fromJson(response, ShoppingAddressEntity.class);
                if (shoppingAddressEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    for (int i = 0; i < shoppingAddressEntity.getData().size(); i++) {
                        ShoppingAddressEntity.ShoppingAddress shoppingAddress = shoppingAddressEntity.getData().get(i);
                        if (shoppingAddress.getDefaultX() == 1) {
                            MyAddressCache.getInstance(getApplication()).saveData(
                                    new MyAddress(shoppingAddress.getId() + "", shoppingAddress.getName(),
                                            shoppingAddress.getMobile(), shoppingAddress.getAddress()));
                        }
                    }
                    initShop();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }


    /**
     * 初始化购买商品
     */
    private void initShop() {
        MyAddress myAddress = MyAddressCache.getInstance(mContext).getData();
        KLog.e(myAddress);
        rl_address.setVisibility(View.VISIBLE);
        if (null == myAddress) {
            ll_address.setVisibility(View.GONE);
            ll_setting_address.setVisibility(View.VISIBLE);
            myAddressId = "";

        } else {
            ll_address.setVisibility(View.VISIBLE);
            ll_setting_address.setVisibility(View.GONE);
            myAddressId = myAddress.getMyAddressId();
            tv_name.setText(myAddress.getName());
            tv_phone.setText(myAddress.getPhone());
            tv_address.setText(myAddress.getAddress());
        }

        ll_money.setVisibility(View.GONE);
        rl_end_date.setVisibility(View.GONE);
        rl_red_package.setVisibility(View.GONE);
        ll_view_title.setVisibility(View.GONE);
        payType = PARAMS_BAY_COMMODITY;
        commodityId = productEntity.getProduct_id();
        mTitle = productEntity.getTitle();
        tv_order_title.setText(mTitle);
        String disPrice = String.format(getString(R.string.text_price), productEntity.getMoney());
        mPrice = String.format(getString(R.string.text_price), productEntity.getMoney());
        tv_discount_price.setText(disPrice);
        tv_total.setText(mPrice);
        Glide.with(mContext).load(productEntity.getCover()).crossFade().error(R.mipmap.icon_default_shop).into(iv_shopbook_image);
    }


    /**
     * 初始化商家转账
     */
    private void initShopPayment() {
        payType = PARAMS_BAY_SHOPTRANSFER;
        commodityId = status_shopDetail.getData().getShop_id();
        ll_shop_payinfo.setVisibility(View.GONE);
        transfer_money = status_shopDetail.getData().getRepostMoney();
    }

    private void startPayResult() {
        if (post != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_POST_ITEM, post);
        }

        if (productsEntity != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_BUY_VIP, productsEntity);
        }

        if (orderDetailEntity != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_ORDER_DETAIL, orderDetailEntity);
        }

        if (status_shopDetail != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_GET_MONEY_2_SHOP, status_shopDetail);
        }

        if (orderDetail != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_PAY_ORDER, orderDetail);
        }

        if (waitPaymentEntity != null) {
            startLocalActivity(PaymentActivity.this, BuyResultActivity.class, PARAMS_WAIT_PAYMENT, waitPaymentEntity);
        }

    }

    @OnClick(R.id.ll_setting_address)
    void setAddress() {
        startActivity(new Intent(mContext, ShoppingAddressActivity.class));
    }

    @OnClick(R.id.ll_address)
    void setNewAddress() {
        startActivity(new Intent(mContext, ShoppingAddressActivity.class));
    }

    @OnClick(R.id.tv_pay)
    void payment() {
        if (productEntity != null) {
            if (TextUtils.isEmpty(myAddressId)) {
                ShowToast.showShortToast("请您选择商品收货地址");
                return;
            }
        }
        if (mHongBao != null && mHongBao.getType().equals(HongBaoEntity.TYPE_POST)) {
            useRedReadPost();
        } else {
            if (payPlatform.equals(TYPE_ALIPAY)) {
                aliPay();
            }
            if (payPlatform.equals(PayTypeEntity.TYPE_WCHAT)) {
                weixinPay();
            }
            if (payPlatform.equals(TYPE_MYPAY)) {
                initPwPopup();
            }
        }
    }


    @OnClick(R.id.rl_red_package)
    void redPackage() {
        startLocalActivity(this, RedActivity.class, PARAMS_RED_TYPE, new RedSelectEvent(type, money));
    }

    // 使用红包查看帖子
    private void useRedReadPost() {
        String url = URL_SHARE_CALL_BACK + commodityId + "/buy/hongBao";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                PostInfoEntity postInfoEntity = GsonUtil.fromJson(response, PostInfoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(postInfoEntity.getStatus_code())) {
                    ShowToast.showShortToast("兑换成功");
                    startPayResult();
                    finish();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }

    private void getRed() {
        OkHttpUtils.get().url(URL_USER_RED)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", "1")
                .addParams("size", "1000")
                .addParams("type", type)
                .addParams("status", "1")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                HongBaoEntity hongBaoEntity = GsonUtil.fromJson(response, HongBaoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(hongBaoEntity.getStatus_code())) {
                    String count = String.format(getText(R.string.text_red_count).toString(),
                            hongBaoEntity.getData().getList().size());
                    if (hongBaoEntity.getData().getList().size() == 0) {
                        count = getString(R.string.text_red_empty);
                    }
                    tv_red_count.setText(count);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }

    /**
     * 余额支付
     */
    private void myPay(String password) {
        mPasswordPayPopup.setTextGoneWheelVisiable();
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            ShowToast.showShortToast(getString(R.string.text_user_pay_info));
            return;
        }
        KLog.e(payType);
        KLog.e(commodityId);
        KLog.e(myAddressId);
        KLog.e(transfer_money);
        KLog.e(password);
//        view_loading.setVisibility(View.VISIBLE);
        PostFormBuilder builder = OkHttpUtils.post();
        builder.url(URL_PAY_MYPAY);
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builder.addParams("type", payType);
        if (payType.equals("3") || payType.equals("5") || payType.equals("6")) {
            builder.addParams("transfer_amount", transfer_money);
        }
        builder.addParams("id", commodityId);
        builder.addParams("address_id", myAddressId);
        builder.addParams("password", password);
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
//                view_loading.setVisibility(View.GONE);
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();
                mPasswordPayPopup.dismiss();
//                                    ShowToast.showShortToast(getString(R.string.text_pay_success));
                startLocalActivity((Activity) mContext, BuyResultActivity.class, EVENT_MY_PAY, String.valueOf(price));
            }

            @Override
            public void onError(Call call, Exception e) {
//                view_loading.setVisibility(View.GONE);
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }

    /**
     * 微信支付
     */
    private void weixinPay() {
        view_loading.setVisibility(View.VISIBLE);
        if (!CommonUtils.isWeixinAvilible(mContext)) {
            ShowToast.showLongToast(getString(R.string.text_install_wchat));
            return;
        }
        KLog.e(payType + "/" + commodityId);
        OkHttpUtils.post().url(URL_PAY_WEIXIN)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", payType)
                .addParams("id", commodityId)
                .addParams("address_id", myAddressId)
                .addParams("transfer_amount", transfer_money)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                KLog.e(response);
                WeChatPayEntity weChatPayEntity = GsonUtil.fromJson(response, WeChatPayEntity.class);
                if (weChatPayEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    weChatPay(weChatPayEntity);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                view_loading.setVisibility(View.GONE);
                e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }

    /**
     * 阿里支付
     */
    private void aliPay() {
        view_loading.setVisibility(View.VISIBLE);
        OkHttpUtils.post().url(URL_PAY_ALIPAY)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", payType)
                .addParams("id", commodityId)
                .addParams("address_id", myAddressId)
                .addParams("hong_bao_id", hongbaoId)
                .addParams("transfer_amount", transfer_money)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                PayInfoEntity payInfoEntity = GsonUtil.fromJson(response, PayInfoEntity.class);
                if (payInfoEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    aliPayment(payInfoEntity);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PaymentActivity.this, status_error);
            }
        });
    }

    // 微信支付
    private void weChatPay(WeChatPayEntity weChatPayEntity) {
        IWXAPI api = WXAPIFactory.createWXAPI(mContext, WECHAT_APP_ID);
        api.registerApp(WECHAT_APP_ID);
        WeChatPayEntity.Data data = weChatPayEntity.getData();
        PayReq payReq = new PayReq();
        payReq.appId = data.getApp_id();
        payReq.partnerId = data.getMerchant_id();
        payReq.prepayId = data.getPrepay_id();
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = data.getNonce_str();
        payReq.timeStamp = data.getTimestamp();
        payReq.sign = data.getSign();
        api.sendReq(payReq);
    }


    // 阿里支付
    private void aliPayment(PayInfoEntity payInfoEntity) {
        final String orderInfo = payInfoEntity.getData().getInfo();
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PaymentActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void initPwPopup() {
        if (null == mPasswordPayPopup) {
            mPasswordPayPopup = new PasswordPayPopup((Activity) mContext);
            mPasswordPayPopup.setAccountName(mTitle);
            mPasswordPayPopup.setBalance(mPrice);
        }
        mPasswordPayPopup.setOnItemClickListener(new PasswordPayPopup.onPasswordPayPopupClickListener() {
            @Override
            public void onItemClick() {
                startLocalActivity((Activity) mContext, ForgetActivity.class, PARAMS_PAY_TRANSFER, PARAMS_PAY_TRANSFER);
            }
        });
        mPasswordPayPopup.setOnClickSurePayListener(new PasswordPayPopup.OnClickSurePayListener() {
            @Override
            public void onClickItem(TextView mTv_sure, ProgressWheel mProgress_wheel, String mPassword) {
                myPay(mPassword);
            }
        });
        mPasswordPayPopup.showPopupWindow();
    }


    private void addHongBao() {
        tv_red_count.setBackgroundResource(R.color.transparent_00000);
        tv_red_count.setTextColor(getResources().getColor(R.color.text_price_red_color));
        switch (mHongBao.getType()) {
            case HongBaoEntity.TYPE_MONEY:
                double total = Double.valueOf(money);
                double hongbao = Double.valueOf(mHongBao.getMoney());
                String totalMoney = new java.text.DecimalFormat("#0.00").format((total - hongbao));
                tv_red_count.setText("-¥" + hongbao);
                tv_total.setText("¥" + totalMoney);
                orderDetailEntity.setDiscount_price(totalMoney);
                hongbaoId = mHongBao.getId();
                break;
            case HongBaoEntity.TYPE_POST:
                ll_money_pay.setVisibility(View.GONE);
                rl_total_money.setVisibility(View.GONE);
                tv_red_count.setText("使用红包");
                break;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        startPayResult();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "取消支付", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_ADDRESS_SUCCESS:
                initShop();
                break;
            case EVENT_WCHAT_PAY_SUCCESS:
                startPayResult();
                finish();
                break;
            case EVENT_MY_PAY:
                finish();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(HongBaoEntity.HongBao hongBaoEntity) {
        if (null != hongBaoEntity) {
            mHongBao = hongBaoEntity;
            addHongBao();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public PasswordPayPopup getPasswordPayPopup() {
        return mPasswordPayPopup;
    }
}
